// pages/saveCard/saveCard.js
const app = getApp()
import {
  cardBillList,
  list
} from '../../../api/card'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showMonth: "",
    pageNum: 1,
    pageSize: 20,
    cardId: "",
    balance: '0.00',
    showDetail: false,
    onTop: false,
    statusBarHeight: 102,
    scrollToIndex: "",
    scrollViewHeight: "",
    month: "2020",
    scrollData: [], //记录要滚动的数据
    iconUrl: ["wallet-consumption.png", "wallet-income.png", "wallet-timeout.png"],
    saveCardDetailList: [],
    cardForm: {}

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getCardList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.calculateScrollData(this.data.saveCardDetailList)
    this.getTop()
    let query = wx.createSelectorQuery()
    query.select('#title').boundingClientRect()
    query.exec((res) => {
      this.setData({
        statusBarHeight: res[0].bottom
      })
    })
  },

  //获取充值卡数据
  getCardList() {
    console.log("请求充值卡数据--")
    list({
      cardType: 0
    }).then(
      res => {
        console.log("接收用户充值卡信息--")
        console.log(res)
        if (res.type == 'success') {
          if (res.data.data.length > 0) {
            this.getCardBill(res.data.data[0].id)
            this.setData({
              cardId: res.data.data[0].id,
              cardForm: res.data.data[0]
            })
          }
        }
      }
    ).catch(error => {
      console.log(error)
    })
  },

  getCardBill(cardId) {
    console.log("请求用户的账户卡和福利金的余额数据--")
    cardBillList({
      cardId: cardId,
      pageSize: this.data.pageSize,
      pageNum: this.data.pageNum
    }).then(
      res => {
        // console.log("接收用户信息--" + JSON.stringify(res.data.data))
        if (res.type == 'success') {
          if (res.data.data.length > 0) {
            this.formatBillList(res.data.data)
          }

        }
      }
    ).catch(error => {
      console.log(error)
    })
  },

  formatBillList(data) {
    // console.info("卡账单数据data--" + JSON.stringify(data))
    //先整理數據
    let monthList = []
    if (data.length > 0) {
      data.map(item => {
        item.createDate = this.formatDate2Time(item.createDate)
        item.month = item.createDate.substring(0, 4) + "年" + item.createDate.substring(5, 7) + "月"

        monthList.push(item.month)
        item.result = item.credit - item.debit
        if (item.type == 0) {
          item.tag = "充值-"
          item.isIncome = true
          item.icon = this.data.iconUrl[1]
        } else
          if (item.type == 2) {
            item.tag = ""
            item.isIncome = true
            item.icon = this.data.iconUrl[1]
          } else if (item.type == 1) {
            item.tag = ""
            item.isIncome = false
            item.icon = this.data.iconUrl[0]
          }
      })
      console.info("卡账单数据data--" + JSON.stringify(data))
      monthList = Array.from(new Set(monthList))
      let addSaveCardDetailList = []
      let saveCardDetailList = this.data.saveCardDetailList
      if (monthList.length > 0) {
        monthList.map((item) => {
          let saveCardDetailListItem = {
            month: item,
            showMonth: item,
            onTop: false,
            saveCardDetail: []
          }
          data.map(item1 => {
            if (item1.month == item) {
              saveCardDetailListItem.saveCardDetail.push(item1)
            }
          })
          addSaveCardDetailList.push(saveCardDetailListItem)
        })
        if (saveCardDetailList.length > 0) {
          addSaveCardDetailList.map(item => {
            let off = true
            saveCardDetailList.map(item1 => {
              if (item1.month == item.month) {
                console.info("我进判断了")
                item1.saveCardDetail = item1.saveCardDetail.concat(item.saveCardDetail)
                off = false
              }
            })
            if (off) {
              saveCardDetailList.push(item)
            }
          })
        } else {
          saveCardDetailList = addSaveCardDetailList
        }
      }
      this.setData({
        showDetail: true,
        saveCardDetailList: saveCardDetailList
      })
      this.getTop()
      // console.info("saveCardDetailList--" + JSON.stringify(this.data.saveCardDetailList))
    }

  },

  getTop() {
    let query = wx.createSelectorQuery()
    // query.select('#title').boundingClientRect()
    query.select('#saveCard-top').boundingClientRect()
    query.select('#saveCard-middle').boundingClientRect()
    query.exec((res) => {
      console.info("节点的res--" + JSON.stringify(res))
      if (res[1] != null) {
        this.calculateScrollData(res)
      }
    })
  },

  //计算滚动事件的参数
  calculateScrollData(data) {
    let viewHeight = data[1].height
    let top = data[0].top
    let bottom = data[0].bottom
    // console.info("viewHeight--" + viewHeight)
    // console.info("top--" + top)
    // console.info("bottom--" + bottom)
    let height = bottom - top
    let saveCardDetailList = this.data.saveCardDetailList
    var scrollData = []
    // let height = this.data.statusBarHeight +120
    if (saveCardDetailList.length > 0) {
      saveCardDetailList.map((item, index) => {
        let scrollDataItem = {}
        scrollDataItem.month = item.month
        scrollDataItem.top = height
        height += (item.saveCardDetail.length + 1) * viewHeight
        scrollDataItem.bottom = height
        scrollData.push(scrollDataItem)
      })
      this.setData({
        scrollData: scrollData
      })
    }
    // console.info("scrollData--" + JSON.stringify(this.data.scrollData))
  },

  //监听页面的滚动事件
  onPageScroll: function (e) {
    // console.log(e.scrollTop);
    let scrollData = this.data.scrollData
    let saveCardDetailList = this.data.saveCardDetailList
    let showMonth = this.data.showMonth
    let onTop = this.data.onTop
    // console.info("scrollData-- " + JSON.stringify(scrollData))

    if (scrollData.length > 0) {
      scrollData.map((item) => {
        if (e.scrollTop >= item.top && e.scrollTop <= item.bottom) {
          onTop = true
          console.info("该我了")
          if (saveCardDetailList.length > 0) {
            saveCardDetailList.map((item1) => {
              if (item1.month == item.month) {
                // item1.onTop = true
                showMonth = item.month
              } else {
                // item1.onTop = false
              }
            })
          }
        } else if (e.scrollTop < scrollData[0].top) {
          console.info("还不是时候")
          onTop = false
          // saveCardDetailList[0].onTop = false         
        }
      })
      this.setData({
        onTop: onTop,
        showMonth: showMonth,
        // saveCardDetailList: saveCardDetailList
      })
      console.info("onTop--" + JSON.stringify(this.data.onTop))
      console.info("statusBarHeight--" + JSON.stringify(this.data.statusBarHeight))
    }
  },



  //上啦加载
  onReachBottom(e) {
    console.info("下拉加载被触发了")
    this.data.pageNum++
    console.info("this.data.pageNum" + this.data.pageNum)
    this.getCardBill(this.data.cardId)
  },

  //时间格式化器
  formatDate2day(val) {
    let date = new Date(val);
    let y = date.getFullYear();
    let MM = date.getMonth() + 1;
    MM = MM < 10 ? ('0' + MM) : MM;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    return y + '-' + MM + '-' + d;
  },

  formatDate2Time(val) {
    let date = new Date(val);
    let y = date.getFullYear();
    let MM = date.getMonth() + 1;
    MM = MM < 10 ? ('0' + MM) : MM;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    let h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    let m = date.getMinutes();
    m = m < 10 ? ('0' + m) : m;
    let s = date.getSeconds();
    s = s < 10 ? ('0' + s) : s;
    return y + '-' + MM + '-' + d + " " + h + ":" + m + ":" + s;
  },
  toSaveCard: function (e) {
    wx.navigateTo({
      url: '/pages/member/saveCard/saveCard',
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  topUpClick(){
    wx.showToast({
      title: '暂未开通',
    })
  }
})